package com.zust.data.web.adapter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author senselyan
 * @Description: 拦截器
 * @date 2018/5/7 17:38
 */
@Component
public class BasePathInterceptor implements HandlerInterceptor {

    private Logger logger = LoggerFactory.getLogger(BasePathInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String scheme = request.getScheme();
        String serverName = request.getServerName();
        int port = request.getServerPort();
        String path = request.getContextPath();
        String basePath = scheme + "://" + serverName + ":" + port + path;
        request.setAttribute("basePath", basePath);

        HttpSession session = request.getSession();
        if (request.getRequestURI().equals("/user/login")
                || request.getRequestURI().equals("/user/doLogin")
                || request.getRequestURI().equals("/user/reg")
                || request.getRequestURI().equals("/user/doReg")
                ) {
            return true;
        } else {
            //判断用户ID是否存在，不存在就跳转到登录界面
            if (ObjectUtils.isEmpty(session.getAttribute("sessionInfo"))) {
                logger.info("------:跳转到login页面！");
                response.sendRedirect("/user/login");
                return false;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

}